import classNames from 'classnames'
import styles from './base-info.module.scss'
import { useState } from 'react'
import { Flex, Input, Button, message } from 'antd'
import { edit, getInfo } from '@/api/user'
import { useDispatch } from 'react-redux'

const BaseInfo = () => {
  /**
   * 变量集合
   */

  const userInfostr = localStorage.getItem('userInfo') || ''
  const userInfo = JSON.parse(userInfostr)
  const [list, setList] = useState([
    { id: 1, label: '昵称', value: userInfo?.name || '', isShowBtn: false, param: 'name' },
    { id: 2, label: '手机号', value: userInfo?.phone || '', isShowBtn: false, param: 'phone' },
    { id: 3, label: '邮箱', value: userInfo?.email || '', isShowBtn: false, param: 'email' }
  ])
  const [isloading, setLoading] = useState(false)
  const [messageApi, contextHolder] = message.useMessage() //消息提示框
  const dispatch = useDispatch()

  /**
   * 设置value
   */
  /**
   * setList(prevList => [
      { ...prevList[0], value: userInfo?.name || '' },
      { ...prevList[1], value: userInfo?.phone || '' },
      { ...prevList[2], value: userInfo?.email || '' }
    ])
   */

  /**
   * 确定
   */
  const changeValue = (value: string, index: number) => {
    setList(prevList => prevList.map((item, i) => (i === index ? { ...item, value: value } : item)))
    if (value !== userInfo[list[index].param]) {
      setList(prevList => prevList.map((item, i) => (i === index ? { ...item, isShowBtn: true } : item)))
    } else {
      setList(prevList => prevList.map((item, i) => (i === index ? { ...item, isShowBtn: false } : item)))
    }
  }
  const confirm = async (index: number) => {
    setLoading(true)
    try {
      const res = await edit({ column: list[index].param, value: list[index].value }, userInfo?.id)
      if (res.code < 200 || res.code > 399) {
        const error = typeof res.message === 'object' ? JSON.stringify(res.message) : res.message
        return messageApi.open({
          type: 'error',
          content: '编辑失败,请稍后再试: ' + error,
          duration: 5
        })
      }
      messageApi.open({
        type: 'success',
        content: '编辑成功'
      })
      const user = await getInfo()
      dispatch({ type: 'setUserInfo', val: user.data })
    } catch (error) {
      console.log('发生了错误: ', error)
    } finally {
      setLoading(false)
    }
  }
  return (
    <>
      {contextHolder}
      <div className={classNames(styles.box_base_info)}>
        {list.map((item, index) => (
          <div key={item.id} className={classNames(styles.list_item)}>
            {item.label}
            <Flex vertical={false} align="center">
              {/* [8, 16] 上下 左右 */}
              <Flex vertical={false} align="center" gap={20} flex={1}>
                <Input style={{ width: '50%' }} value={item.value} onChange={e => changeValue(e.target.value, index)} />
                {item.isShowBtn && (
                  <Button type="primary" loading={isloading} onClick={() => confirm(index)}>
                    确定
                  </Button>
                )}
              </Flex>
            </Flex>
          </div>
        ))}
      </div>
    </>
  )
}

export default BaseInfo
